package com.yungee.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class JsonUtil {

    private  Logger log = LoggerFactory.getLogger(getClass());
    /**
     * 时间格式化
     */
    private static final ThreadLocal<SimpleDateFormat> dateFormatLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private static ThreadLocal<ObjectMapper> objMapper = new ThreadLocal<ObjectMapper>() {
        @Override
        protected ObjectMapper initialValue() {
            ObjectMapper newInstance = new ObjectMapper();
            newInstance.setDateFormat(dateFormatLocal.get());
            return newInstance;
        }
    };
    public static String toJson(Object o) {
        try {
            return objMapper.get().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONObject toJsonObject(Object o) {
        try {
            String str = objMapper.get().writeValueAsString(o);
            return JSONObject.parseObject(str);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromJson(String value, Class<T> clazz) {
        try {
            return objMapper.get().readValue(value, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromJson(String value, TypeReference<T> typeReference) {
        try {
            return objMapper.get().readValue(value, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}